<template>
  <div class="app-container">
    <div class="filter-container clearfix">
      <!-- <el-select v-model="listQuery.sid" class="filter-item" style="width: 130px;" filterable clearable :loading="loading" placeholder="选择区服">
        <el-option v-for="item in serverList" :key="item.sid" :label="item.name + '(' + item.sid + ')'" :value="item.sid">
        </el-option>
      </el-select> -->
      <el-select v-model="listQuery.activity_type" class="filter-item" style="width: 130px;" filterable clearable placeholder="赛季">
        <el-option v-for="item in seasonList" :key="item.id" :label="item.label" :value="item.id">
        </el-option>
      </el-select>
      <statisSearchBar :start-date="listQuery.start_date" :end-date="listQuery.end_date" :showp-pf-channel="false" :show-channel="false" @transferFilter="crossServerGroupList" />
      <el-button v-if="checkPermission(permissionRoles.cross_server_config)" type="primary" @click="handleConfig">匹配设置</el-button>
    </div>
    <div style="min-height: 670px;">
      <el-table
        ref="table"
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa' }"
        :row-class-name="tableRowClassName"
        stripe
      >
        <el-table-column prop="id" label="战区ID" width="80"></el-table-column>

        <!-- 服务器主列 -->
        <el-table-column
          label="服务器"
          align="center"
          :render-header="renderServerHeader"
        >
          <!-- 动态生成子列 -->
          <el-table-column
            v-for="(col, index) in maxServerCount"
            :key="index"
            :prop="'servers.' + index"
            :label="''"
            width="200"
            show-overflow-tooltip
          >
            <template slot-scope="{ row }">
              {{ row.servers[index] || '' }}
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column prop="fightNum" label="战区人数" width="100"></el-table-column>
        <el-table-column prop="status_name" label="状态" width="100"></el-table-column>
        <el-table-column prop="activity_type_name" label="所属赛季" width="100"></el-table-column>
        <el-table-column prop="match_end_date" label="匹配结束时间" width="120"></el-table-column>
        <el-table-column prop="start_date" label="赛季开始时间" width="120"></el-table-column>
        <el-table-column prop="end_date" label="赛季结束时间" width="120"></el-table-column>
        <el-table-column v-if="list_type === 1" align="center" label="操作" width="120px" fixed="right">
          <template slot-scope="{row}">
            <el-button
              v-if="checkPermission(permissionRoles.cross_server_group_edit) && (row.status == 0)"
              type="text"
              @click="handleConfirm(row)"
            >确认</el-button>
            <el-button
              v-if="checkPermission(permissionRoles.cross_server_group_edit) && (row.status == 1 || row.status == 0)"
              type="text"
              @click="handleEdit(row)"
            >修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="crossServerGroupList" />
    <el-dialog :visible.sync="dialogVisible" :title="textMap[dialogType]" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="dataForm" label-width="80px" label-position="left">
        <el-form-item label="战区ID" prop="id">
          <el-input v-model="dataForm.id" :disabled="idDisabled" class="defaut-input" placeholder="填写大区ID" />
        </el-form-item>
        <el-form-item label="服务器">
          <el-row>
            <el-col :md="3"><el-button type="primary" class="add" icon="el-icon-plus" @click="serverAdd">新增</el-button></el-col>
          </el-row>
          <el-row v-for="(item, index) in dataForm.items" :key="index" class="mt-5" :gutter="12">
            <el-col :md="6">
              <el-select v-model="item.sid" clearable filterable placeholder="请选择服务器" onchange="test">
                <el-option v-for="p in serverList" :key="p.sid" :label="p.name" :value="p.sid" />
              </el-select>
            </el-col>
            <el-col :md="4"><el-button type="danger" icon="el-icon-delete" @click.prevent="remove(item)" /></el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="configVisible" title="战区匹配设置" :close-on-click-modal="false">
      <el-form ref="configForm" :model="configForm" label-width="120px" label-position="left">
        <el-form-item label="匹配战区数量" prop="id">
          <el-input v-model="configForm.cross_server_config_num" class="defaut-input" placeholder="填写战区数量D" />
        </el-form-item>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="configVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmConfigSubmit()">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { deepClone } from '@/utils'
import checkPermission from '@/utils/permission'
import Pagination from '@/components/Pagination'
import StatisSearchBar from '@/components/StatisSearchBar'
import { getCrossServerConfigNum, handleConfigNum, crossServerGroupList, handleCrossServerParam, crossServerServerList, crossServerGroupTypeList } from '@/api/ops'

const defaultItem = {
  id: '',
  items: [{
    sid: ''
  }]
}
export default {
  name: 'CrossServerGroup',
  components: { Pagination, StatisSearchBar },
  props: {
    list_type: { type: Number, default: 1 }
  },
  watch: {
    dataForm(value) {
      console.log(value)
    }
  },
  data() {
    return {
      tableData: [],
      maxServerCount: 4,
      permissionRoles: this.$store.state.user.permissionRoles,
      listLoading: false,
      dataForm: Object.assign({}, defaultItem),
      configForm: {
        cross_server_config_num: ''
      },
      serverList: [],
      seasonList: [],
      list: [],
      dialogVisible: false,
      configVisible: false,
      idDisabled: false,
      battleSwitch: '0',
      channelList: [],
      srid: '',
      srname: '',
      dialogType: 'new',
      textMap: {
        edit: '编辑',
        new: '新增'
      },
      listQuery: {
        page: 1,
        limit: 200,
        sids: '',
        activity_type: '',
        start_date: '',
        end_date: ''
      },
      total: 0
    }
  },
  computed: {
  },
  created() {
    this.crossServerGroupList()
    this.crossServerServerList()
    this.crossServerGroupTypeList()
    this.getCrossServerConfigNum()
  },
  mounted: function() {
    this.$nextTick(() => {
      const table = this.$refs.table
      const headerRow = table.$el.querySelector('.el-table__header-wrapper tr')
      const thList = headerRow ? Array.from(headerRow.querySelectorAll('th')) : []

      if (thList.length > 0) {
        // 假设 "服务器" 是第2个表头列（索引为1）
        const serverTh = thList[1]
        if (serverTh) {
          serverTh.setAttribute('rowspan', '2')
        }
      }
    })
  },
  methods: {
    checkPermission,
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row'
      } else if (rowIndex === 3) {
        return 'success-row'
      }
      return ''
    },
    async crossServerGroupTypeList() {
      const list = await crossServerGroupTypeList()
      this.seasonList = list.data
    },
    async crossServerGroupList(qu) {
      if (qu) {
        this.listQuery.sids = qu.servers
      }
      const query = Object.assign(this.listQuery, { type: this.list_type })
      const list = await crossServerGroupList(query)
      this.tableData = list.data.items
      this.total = list.data.total
      this.maxServerCount = list.data.maxServerCount
    },
    async crossServerServerList(query) {
      const list = await crossServerServerList(query)
      const serverList = list.data.map(item => ({
        ...item, // 保留原有的其他属性
        sid: '' + item.sid // 将 sid 转换为字符串
      }))
      this.serverList = serverList
    },
    async getCrossServerConfigNum() {
      const datas = await getCrossServerConfigNum()
      this.configForm = datas.data
    },
    handleConfig() {
      this.configVisible = true
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.idDisabled = true
      const data = deepClone(row)
      this.dataForm = {
        id: data.id,
        items: data.sids.map(sid => ({ sid: '' + sid }))
      }
      const query = {}
      if (data.cross_alone_server) {
        query.srid = data.srids
      }
      this.crossServerServerList(query)
    },
    handleConfirm(row) {
      const name = '确认匹配完成'
      const oldValue = 0
      const action = '确认'
      const field = 'status'
      this.$confirm('你确定要' + action + name + '?', name + '开关', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const data = {
            id: row.id
          }
          data[field] = 1
          handleCrossServerParam(data).then(response => {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.crossServerGroupList()
          })
        })
        .catch(err => {
          console.error(err)
          row[field] = oldValue
        })
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const sids = this.dataForm.items.map(item => item.sid)
          const data = { id: this.dataForm.id, sids: sids }
          handleCrossServerParam(data).then(response => {
            if (response.status) {
              this.dialogVisible = false
              this.crossServerGroupList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            }
          })
        }
      })
    },
    confirmConfigSubmit() {
      handleConfigNum(this.configForm).then(response => {
        if (response.status) {
          this.configForm = false
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        }
      })
    },
    serverAdd() {
      this.dataForm.items.push({
        id: ''
      })
    },
    remove(row) {
      var index = this.dataForm.items.indexOf(row)
      if (index !== -1) {
        this.dataForm.items.splice(index, 1)
      }
    },
    renderServerHeader(h, { column }) {
      return h(
        'div',
        {
          style: {
            textAlign: 'center',
            fontWeight: 'bold'
          },
          attrs: {
            colSpan: 1, // 跨列数
            rowspan: 2
          }
        },
        '服务器'
      )
    },
    test() {
      console.log(this.dataForm)
    }
  }
}
</script>
<style lang="scss" scoped>
.el-table {
  font-size: 14px;
}

.el-table td,
.el-table th {
  padding: 10px 0;
}

.el-table th>.cell {
  padding-left: 10px;
  padding-right: 10px;
}
.el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>
